package com.example.myproject.controller;


import com.example.myproject.model.Customer;
import com.example.myproject.model.Role;
import com.example.myproject.service.CustomerService;
import com.example.myproject.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/customer")
public class CustomerController {

    private final CustomerService customerService;

    @Autowired
    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @PostMapping("/add")
    public Result<Customer> addCustomer(@RequestBody Customer customer) {
        Customer addedcustomer = customerService.addCustomer(customer);
        if(customer!=null){
            return Result.success(addedcustomer,"新建角色成功！");

        }else{
            return Result.error("123","新建客户失败！");
        }
    }

//    @GetMapping("/search/{name}")
//    public Result<Optional<Customer>>  getCustomerByName(@PathVariable String name) {
//        Optional<Customer> customer = Optional.ofNullable(customerService.getCustomerByName(name));
//        if (customer != null) {
//            return Result.success(customer, "查找客户成功！");
//        } else {
//            return Result.error("404", "角色不存在！");
//        }
//
//    }

    @GetMapping("/get")
    public Result<List<Customer>> getAllCustomers() {
        List<Customer> customers = customerService.getAllCustomers();
        return Result.success(customers, "查找所有角色成功！");
    }

    @PutMapping("/edit/{name}")
    public Result<Customer> updateCustomer(@PathVariable String name, @RequestBody Customer customerDetails) {
        Customer updatedCustomer = customerService.updateCustomer(name, customerDetails);
        if(updatedCustomer!=null){
            return Result.success(updatedCustomer,"修改角色成功！");

        }else{
            return Result.error("123","修改角色失败！");
        }
    }
    @GetMapping("/search")
    public Result<List<Customer>> searchCustomersByName(@RequestParam(required = false) String name) {
        if (name == null || name.isEmpty()) {
            // 如果接收内容为空，则调用已经存在的查找所有角色的方法
            return getAllCustomers();
        } else {
            List<Customer> customers;
            customers = customerService.getCustomerByName(name);
            if (!customers.isEmpty()) {
                return Result.success(customers, "根据角色名搜索角色成功！");
            } else {
                return Result.error("404", "没有找到符合条件的角色！");
            }
        }
    }

    @DeleteMapping("/delete/{name}")
    public Result<Customer> deleteCustomer(@PathVariable String name) {
        customerService.deleteCustomer(name);
        return Result.success(null, "删除客户成功！");
    }
}
